<?php
require_once("redisDb.php" ); //自己简单些的redis类
require_once("rndChinaName.php" ); //用于随机生成名字
class server{
    private $redis;
    private $randName;
    public 	function __construct(){
        $this->redis = new redisDb();
        $this->randName = new rndChinaName();
        $this->redis->flushAll();
        echo "redis is connect";
    }
    public  function getChar($num)  // $num为生成汉字的数量
    {
        $b = '';
        for ($i=0; $i<$num; $i++) {
            // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节
            $a = chr(mt_rand(0xB0,0xD0)).chr(mt_rand(0xA1, 0xF0));
            // 转码
            $b .= iconv('GB2312', 'UTF-8', $a);
        }
        return $b;
    }
    public function getName(){
        return $this->randName->getName();
    }
    public function socket(){
        //创建websocket服务器对象，监听0.0.0.0:9502端口
        $ws = new swoole_websocket_server("0.0.0.0", 9502);
        $ws->set([
//			'socket_buffer_size' => 128 * 1024 *1024, //必须为数字
            'worker_num' => 2,
            'task_worker_num' =>4,
        ]);
        //监听WebSocket连接打开事件
        $ws->on('open', function ($ws, $request) {
            $room = "xyf";
            $name = $this->getName();
            $this->redis->hset($room,$request->fd,$name);
            $Pnum = $this->redis->hlen($room);
            $json = array('type'=>'3','message'=>"欢迎 <span class='text-navy'>$name</span> 加入聊天室",'time'=>date('Y-m-d H:i:s',time()),'num'=>"在线人数：".$Pnum);
            $str = json_encode($json);
            foreach($ws->connections as $fd){
                $ws->push($fd,$str);
            }
        });

        //监听WebSocket消息事件
        $ws->on('message', function ($ws, $frame) {
            echo "message:{$frame->data}";
            $task_id = $ws->task($frame);
        });

        //监听WebSocket连接关闭事件
        $ws->on('close', function ($ws, $fd) {
            $name = $this->redis->hget("xyf",$fd);
            $this->redis->hdel("xyf",$fd);
            $Pnum = $this->redis->hlen("xyf");
            $json = array('type'=>'3','message'=>"<span class='text-navy'>$name</span> 离开聊天室",'time'=>date('Y-m-d H:i:s',time()),'num'=>"在线人数：".$Pnum);
            $str = json_encode($json);
            foreach($ws->connections as $fd1){
                if($fd1 != $fd){
                    $ws->push($fd1,$str);
                }
            }
            echo "client-{$fd} is closed\n";
        });

        $ws->on('Receive', function(swoole_server $ws, $fd, $from_id, $data) {
            echo "接收数据" . $data . "\n";
            $data = trim($data);
            $task_id = $ws->task($data, 0);
            $ws->send($fd, "分发任务，任务id为$task_id\n");
        });

        $ws->on('Task', function (swoole_server $ws, $task_id, $from_id,$frame) {
            echo "Tasker进程接收到数据";
            foreach($ws->connections as $fd){
                echo "task_id:".$task_id."\n";
                $num = $frame->fd%10;
                $data = htmlspecialchars($frame->data);
                $name = $this->redis->hget("xyf",$frame->fd);
                if($fd==$frame->fd){
                    $json = array('name'=>"$name",'message'=>"$data",'time'=>date('Y-m-d H:i:s',time()),'type'=>'1','img'=>$num);
                }else{
                    $json = array('name'=>"$name",'message'=>"$data",'time'=>date('Y-m-d H:i:s',time()),'type'=>'2','namet'=>"中文",'img'=>$num);
                }
                $str = json_encode($json,JSON_UNESCAPED_UNICODE);
                $ws->push($fd,$str);
            }
            $ws->finish($data);
        });

        $ws->on('Finish', function (swoole_server $ws, $task_id, $data) {
            echo "Task#$task_id finished, data_len=".strlen($data).PHP_EOL."\n";
        });
        $ws->start();
    }
}
$wser = new server();
$wser->socket();
?>
